package filter;

import constutil.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Gong
 * @Description
 * @dATE 2022/4/20 14:36
 **/
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init LoginFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //如果用户未登录，我们强制跳转到登录页
        System.out.println("do filter");
        //当访问/chat/ , /chat/index.jsp ,/chat/loginServlet
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String requestURI = req.getRequestURI();
        System.out.println("当前路径URI:"+requestURI);

        if(!(null!= requestURI && (
                requestURI.equals(req.getContextPath())
                || requestURI.equals(req.getContextPath() + "/"))
                || requestURI.equals(req.getContextPath() + "/index.jsp")
                || requestURI.equals(req.getContextPath() + "/loginServlet"))
                || requestURI.toLowerCase().endsWith(".css")
                || requestURI.toLowerCase().endsWith(".js")
                || requestURI.toLowerCase().endsWith(".png")
                || requestURI.toLowerCase().endsWith(".jpg")
                || requestURI.toLowerCase().endsWith(".webp")
        ){
            //验证是否登录成功
            HttpSession session = req.getSession();
            Object attribute = session.getAttribute(Constants.SESSION_USER_ID);
            if(null == attribute){
//                登录不成功
                //重定向到登录页
                req.setAttribute(Constants.LOGIN_INFO,"抱歉，没登录，请登录再试试。");
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("destroy LoginFilter");
    }
}
